import enLocale from '@/i18n/en/en-US'
import zhLocale from '@/i18n/zh/zh-CN'
import { reactive } from 'vue'
import { get } from './utils'

const locale = reactive({
  lang: localStorage.getItem('v_form_locale') || 'zh-CN'
})

const langResources = {
  'en-US': {
    something: {
      //...
    },
    ...enLocale
  },

  'zh-CN': {
    something: {
      //...
    },
    ...zhLocale
  }
}

export function createI18n(options) {
  return {
    messages: options.messages,

    $st(path, ...args) {
      const message = get(this.messages[locale.lang], path)
      return typeof message === 'function' ? message(...args) : message !== null ? message : path
    },

    $st2(path, path2) {
      let messages = this.messages[locale.lang]
      const message = get(messages, path)
      return message !== null ? message : get(messages, path2)
    },

    setLang(lang) {
      locale.lang = lang
    }
  }
}

const i18n = createI18n({
  locale: localStorage.getItem('v_form_locale') || 'zh-CN',
  messages: langResources
})

export const changeLocale = function (langName) {
  i18n.setLang(langName)
  localStorage.setItem('v_form_locale', langName)
}

export const translate = function (key) {
  return i18n.$st(key)
}

export const useI18n = (app) => {
  app.config.globalProperties.i18nt = (key) => i18n.$st(key)
  app.config.globalProperties.i18n2t = (key1, key2) => i18n.$st2(key1, key2)
}

export default {
  methods: {
    i18nt(key) {
      return i18n.$st(key)
    },

    /* 如果key1不存在，则查找key2 */
    i18n2t(key1, key2) {
      return i18n.$st2(key1, key2)
    }
  }
}
